package account

import (
	"NovelBook/dao"
	"fmt"
	"math/rand"
	"time"
)

// CaptChaDuration 验证码有效期15分钟
const CaptChaDuration = time.Minute * 15

func SetCaptcha(email string) (string, error) {
	num := generateVerificationCode()
	err := dao.Set(email, num, CaptChaDuration)
	if err != nil {
		return "", err
	}
	return num, err
}

// GetCaptcha 获取验证码
func GetCaptcha(email string) (string, error) {
	captcha, err := dao.Get(email)
	if err != nil {
		return "", err
	}
	return captcha, nil
}

// 获取随机的6位数字
func generateVerificationCode() string {
	// 创建随机数源
	source := rand.NewSource(time.Now().UnixNano())
	// 创建随机数生成器
	r := rand.New(source)
	// 生成六位随机数字验证码
	code := ""
	for i := 0; i < 6; i++ {
		// 生成0到9之间的随机整数
		num := r.Intn(10)
		// 将随机整数转换为字符串并拼接到验证码字符串中
		code += fmt.Sprint(num)
	}
	return code
}
